package logic

import (
	"context"
	"errors"
	"math/rand"
	"novel/models/cache"
	"strconv"
	"time"

	"novel/novelrpc/internal/svc"
	"novel/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 短信验证码
func (l *SendSmsLogic) SendSms(in *novelrpc.SendSmsRequest) (*novelrpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	code := rand.Intn(9000) + 1000
	i, _ := cache.Rdb.Get(l.ctx, "data"+in.Phone).Int64()
	if i >= 1 {
		return nil, errors.New("一分钟只能发送一条短信")
	}
	//sms, err := pkg.SendSms(in.Phone, strconv.Itoa(code))
	//if err != nil {
	//	return nil, err
	//}
	//if sms.Code != 2 {
	//	return nil, errors.New("验证码发送失败")
	//}
	cache.Rdb.Set(l.ctx, "sendSms"+in.Phone, code, time.Minute*5)
	cache.Rdb.Set(l.ctx, "data"+in.Phone, 1, time.Minute*1)
	return &novelrpc.SendSmsResponse{
		Code: strconv.Itoa(code),
	}, nil
}
